# Code for Table M1, Row 4: Finer-grain offense covariates

rm(list = ls())

## ---------------------------------------
## Load Packages 
## ---------------------------------------
require('AER')
require('ivpack')
require('dplyr')
require('data.table')

## ---------------------------------------
## Load Data and Functions
## ---------------------------------------
load("../data0812.RData")

directory <- "../functions/"
functions <- list.files(directory)  
loadfunctions <- sapply(functions, FUN = function(x)source(paste0(directory, x)))

## ---------------------------------------
# Construct Instrument
## ---------------------------------------
data0812 <- constructIV(data0812)

## ---------------------------------------
#  Select Last Case Before Election
## ---------------------------------------
data0812 <- lastCase(data0812)

## ---------------------------------------
## Two Stage Least Squares Specifications
## ---------------------------------------

time.controls <- "as.factor(court_time1) + as.factor(court_time2) + as.factor(court_dow) + as.factor(court_shift) + as.factor(totOGS2)"
case.controls_3 <- "as.factor(robbery) +  as.factor(aggAss) + as.factor(theft) +  as.factor(simpAssault) + as.factor(possess) + as.factor(drugSell) + as.factor(drugBuy) + as.factor(possMar) + as.factor(F3firearm) + as.factor(stolProp) + as.factor(vandal) + as.factor(DUI1st) + as.factor(trespass) + as.factor(recklessEndanger) +  as.factor(prior_offender_2) + as.factor(prior_guilt_doc) + as.factor(prior_felChar_doc) + as.factor(prior_violCrime_doc)"
demo.controls <- "age_2012 + I(age_2012^2) + Female + as.factor(race) + vote2008 + as.factor(noteli08) + regis_before"

outc.1 <- "vote2012"
endo.1 <- "pti"
inst.1 <- "judgeiv"

form.3 <- formula(paste(outc.1, "~", endo.1, "+" , time.controls, "+", demo.controls, "+", case.controls_3, "|", inst.1, "+", time.controls, "+", demo.controls, "+", case.controls_3))

m1a3 <- ivreg(form.3, data = data0812)

m1a3D <- summary(m1a3, diagnostic = T)$diagnostics[1, 3]

cont <- data.table(round(rbind(c(robust.se(m1a3)[2, c(1)]),
                               c(robust.se(m1a3)[2, c(2)]),
                               c(m1a3D),
                               c(m1a3$n)
),3))

cat("\nPrinting Table M1, row 4: Finer Grain Offenses...\n")
colnames(cont) <- c("(3)")
# add row labels
cont$names <-  c("Pretrial Incarceration (PTI)",
                 "Std. Error",
                 "F-test", 
                 "Obs.")
cont <- cont[, c("names", "(3)")]

print(cont)
